<?php
namespace app\common\service;;


use think\facade\Db;
use \GatewayWorker\Lib\Gateway;

/**
 * Class MyOrder
 * @package app\common\service
 * 我的订单
 */
class Chat extends Base {

    static $AUTH_CHECK = false; //默认必须登录
    public function _initialize(){
        Gateway::$registerAddress = '127.0.0.1:1236';
    }
    //获取聊天列表
    public function chat_lists(){
        $domain_url = getCurUrl();
        $page = input('pagenum');
        $limit = input('limit')?:15;
        $user_id = 1;
        $field = 'c.*,u.head_pic,u.nickname';
        $map = [];
        $map['c.user_id'] = $user_id;
        //向上翻页，从最后一条开始查询
        $lists = Db::name('chat')
            ->alias('c')
            ->join('users u','c.to_user_id=u.user_id')
            ->where($map)
            ->order('c.w_time desc')
            ->field($field)
            ->paginate($limit,false,['page'=>$page,'list_rows'=>$limit]);
        $default_head = $domain_url.'/static/img/touxiang.png';
        if($lists->total()){
            $data = $lists->items();
            foreach($data as $k=>$v){
                $data[$k]['w_time'] = date('Y-m-d H:i:s',$v['w_time']);
                $data[$k]['nickname'] = $v['nickname']?:'匿名用户';
                $data[$k]['head_pic'] = $v['head_pic']?:$default_head;
            }
        }
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $data,
        ];
        return $result;
    }
    /**
     * 获取聊天记录
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 订单列表数据
     */
    public function lists(){
        $domain_url = getCurUrl();
        $page = input('pagenum');
        $limit = input('limit')?:15;
        //列表过滤器，生成查询Map对象
        $chat_id = input('chat_id')?:1;
        $chat_info = Db::name('chat')->where('id',$chat_id)->find();
        $user_avatar = Db::name('users')->where('user_id',$chat_info['user_id'])->value('head_pic');
        $user_avatar = $user_avatar?$user_avatar:$domain_url.'/static/img/touxiang.png';
        $to_user_avatar = Db::name('users')->where('user_id',$chat_info['to_user_id'])->value('head_pic');
        $to_user_avatar = $to_user_avatar?$to_user_avatar:$domain_url.'/static/img/touxiang.png';
        $order_by = input('order_by');//1向下翻页 2向上翻页
        //查询订单列表
        $field = '*';
        $map = [];
        $map['chat_id'] = $chat_id;
        $count = Db::name('chat_lists')
            ->where($map)
            ->count();
        if($order_by==1){
            //最新数据，查询最后一页
            if($count>=$limit){
                $limit_s = $count-$limit;
            }else{
                $limit_s = 0;
            }
            $last_page = ceil($count/$limit);
            if($page>$last_page){
                $data = [];
            }else{
                $data = Db::name('chat_lists')
                    ->where($map)
                    ->order('id asc')
                    ->field($field)
                    ->limit($limit_s,$count)->select();
            }
        }else{
            //向上翻页，从最后一条开始查询
            $lists = Db::name('chat_lists')
                ->where($map)
                ->order('id desc')
                ->field($field)
                ->paginate($limit,false,['page'=>$page,'list_rows'=>$limit]);
            if($lists->total()){
                $data = $lists->items();
            }
            $last_page = $lists->currentPage();
        }
        if($data){
            foreach($data as $k=>$v){
                $data[$k]['text'] = $v['content'];
                if($v['user_id']==$chat_info['user_id']){
                    $data[$k]['avatar'] = $user_avatar;
                }else{
                    $data[$k]['avatar'] = $to_user_avatar;
                }
                if($v['user_id']==$this->user_id){
                    $data[$k]['is_self'] = 1;
                }else{
                    $data[$k]['is_self'] = 0;
                }
                $data[$k]['show_time'] = 1;
            }
        }
        try {
            $is_online = Gateway::isUidOnline($chat_info['to_user_id'])?1:0;
        }catch (\Exception $e){
            $is_online = 0;
        }
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $data,
            'pagenum' => $last_page,
            'is_online' => $is_online,
        ];
        return $result;
    }
    //发送消息
    public function send_msg(){
        $chat_id = input('chat_id');
        $content_arr = input('content/a');
        $type = input('type')?:'text';
        $content = '';
        $video_cover = '';
        if($type=='image'){
            $content = $content_arr['url'];
        }elseif($type=='text'){
            $content = $content_arr['text'];
        }elseif($type=='video'){
            $content = $content_arr['url'];
            $video_cover = $content_arr['video_cover'];
        }elseif($type=='voice'){
            $content = $content_arr['url'];
            $video_cover = $content_arr['video_cover'];
        }
        if(!$content){
            $result = [
                'status' => false,
                'msg' => '发送内容不能为空',
                'data' => '',
            ];
            return $result;
        }
        $chat_info = Db::name('chat')->where('id',$chat_id)->find();
        $time = time();
        $log = [
            'chat_id' => $chat_id,
            'user_id' => $this->user_id,
            'content' => $content,
            'video_cover' => $video_cover,
            'type' => $type,
            'w_time' => $time,
        ];
        if($this->user_id==$chat_info['user_id']){
            $log['is_self'] = 1;
            $to_user_id = $chat_info['to_user_id'];
        }else{
            $log['is_self'] = 0;
            $to_user_id = $chat_info['user_id'];
        }
        $id = Db::name('chat_lists')->insertGetId($log);
        $domain_url = getCurUrl();
        $user_avatar = $this->user['head_pic']?:$domain_url.'/static/img/touxiang.png';
        $is_self = $this->user_id==$chat_info['user_id']?0:1;
        $res_data = [
            "id" => $id,
            "content" => $content,
            'video_cover' => $video_cover,
            "type" => $type,
            "is_self" => $is_self,
            "avatar" => $user_avatar,// 头像
            "show_time" => true,
            "w_time" => $time,
            "chat_id" => $chat_id,
            "to_user_id" => $to_user_id,
        ];
        $client_id = Gateway::getClientIdByUid($to_user_id);
        writeLog('发消息前会员id::'.$to_user_id.''.json_encode($client_id),'send_msg');
        $send_res = Gateway::sendToUid($to_user_id,json_encode(['data'=>$res_data],JSON_UNESCAPED_UNICODE));
        //$send_res = Gateway::sendToAll(json_encode(['data'=>$res_data],JSON_UNESCAPED_UNICODE));
        writeLog(json_encode($send_res),'send_msg');
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $res_data,
        ];
        return $result;
    }
}
